package com.heqiang.controller;

import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import com.heqiang.ue.PublicMsg;
import com.heqiang.utils.UploadHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
public class CommonController {
	private static Logger logger = LoggerFactory.getLogger(UploadHelper.class);
	
	@Autowired
	private UploadHelper uploadHelper;

	@RequestMapping(value = "/Invalid-access", method = RequestMethod.GET)
	public String goListInformation(HttpServletRequest request, HttpServletResponse response) {
		return "/admin/error/404";
	}

	/**
	 * 上传并读取excel里内容，传给前端。
	 * @author Garfield  
	 * @date 2015-6-9 
	 * @param file
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/excelupload", method = RequestMethod.POST)
	@ResponseBody
	public void uploadExcel(@RequestParam(value = "importFile") MultipartFile file, HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		JSONObject jobject = new JSONObject();
		String originalName = file.getOriginalFilename();
		if (!originalName.endsWith(".xls")) {
			jobject.put("success", false);
			jobject.put("desc", "上传文件格式不正确!请上传.xls");
			sendText(response, jobject.toString());
		}
		int sizeLimit = 50 * 1024 * 1024;
		if (file.getSize() > 1024 * 1024) {
			logger.debug("文件大小" + file.getSize() / 1024 / 1024 + "MB");
		} else {
			logger.debug("文件大小" + file.getSize() / 1024 + "KB");
		}
		try {
			jobject = uploadHelper.saveLocalSingleFile(request, file, sizeLimit);
			sendText(response, jobject.toString());
		} catch (Exception e) {
			logger.error("上传文件失败，msg:" + e.getMessage(), e);
			jobject.put("success", true);
			jobject.put("desc", "文件上传失败");
			sendText(response, jobject.toString());
		}
	}

	@RequestMapping(value = "/upload/imageFile", method = RequestMethod.POST)
	public void uploadEditorFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		upload(file, request, response);
	}

	@RequestMapping(value = "/upload/videoFile", method = RequestMethod.POST)
	public void uploadVideoFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		upload(file, request, response);
	}

	@RequestMapping(value = "/ueditor/request", method = RequestMethod.GET)
	public void ueditorRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setHeader("Content-Type", "text/html");
		String action = request.getParameter("action");
		if ("config".equals(action)) {
			response.getWriter().write(PublicMsg.UEDITOR_CONFIG);
			return;
		}
		String rootPath = request.getServletContext().getRealPath("/");
		String result = new ActionEnter(request, rootPath + "WEB-INF/classes").exec();
		if (action != null && (action.equals("listfile") || action.equals("listimage"))) {
			rootPath = rootPath.replace("\\", "/");
			result = result.replaceAll(rootPath, "/");
		}
		response.getWriter().write(result);
	}

	@RequestMapping(value = "/ueditor/request", method = RequestMethod.POST)
	public void ueditorRequestPost(HttpServletRequest request, HttpServletResponse response, MultipartFile file)
			throws Exception {
		uploadEditorFile(file, request, response);
	}

	/**
	 * 图片上传
	 * @Author: huangzhanping
	 * @param:
	 * @return:
	 * Date: 2019/8/16 18:14
	 */
	@RequestMapping(value = "/ajaxfileupload", method = RequestMethod.POST)
	public void upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int sizeLimit = 50 * 1024 * 1024;
		JSONObject jobject = new JSONObject();
		if (null == file) {
			jobject.put("state", "上传文件为空");
			sendText(response, jobject.toString());
			return;
		}
		if (file.getSize() > 1024 * 1024) {
			logger.debug("文件大小为：" + file.getSize() / 1024 / 1024 + "MB");
		} else {
			logger.debug("文件大小为：" + file.getSize() / 1024 + "KB");
		}
		logger.info("文件大小" + file.getSize());
		logger.info("文件大小为：" + file.getSize() / 1024 / 1024 + "MB");
		// 设置响应给前台内容的数据格式
		response.setContentType("text/plain; charset=UTF-8");
		try {
			jobject = uploadHelper.saveSingleFile(request, file, sizeLimit);
			sendText(response, jobject.toString());
		} catch (Exception e) {
			jobject.put("state", "上传失败");
			logger.error("文件上传失败, msg:" + e.getMessage(), e);
			sendText(response, jobject.toString());
		}
	}

	/**
	 * 发送json格式数据
	 *
	 * @throws IOException
	 */
	public static void sendText(HttpServletResponse response, String data) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		writer.write(data);
		writer.flush();
		writer.close();
	}

	@RequestMapping(value = "/ajaxfileuploads", method = RequestMethod.POST)
	public void ajaxUploadSingle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置响应给前台内容的数据格式
		response.setContentType("text/plain; charset=UTF-8");
		int sizeLimit = 50 * 1024 * 1024;
		try {
			Map<String, String> params = new HashMap<String, String>();
			JSONObject object = uploadHelper.saveSingleUpload("", request, sizeLimit, 0, params, "");
			sendText(response, object.toString());
		} catch (Exception e) {
			logger.error("上传文件失败，msg:" + e.getMessage(), e);
			sendText(response, "上传文件失败");
		}
	}
}
